﻿@page "/Account/Manage/Disable2fa"

@using Microsoft.AspNetCore.Identity
@using MyApp.Data
@using MyApp.Identity

@inject UserManager<ApplicationUser> UserManager
@inject UserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ILogger<Disable2fa> Logger

<PageTitle>Disable two-factor authentication (2FA)</PageTitle>

<Heading3>Disable two-factor authentication (2FA)</Heading3>

<div class="max-w-xl">
    <StatusMessage />

    <Alert Type="AlertType.Warning">
        <p class="mb-3">
            <strong>This action only disables 2FA.</strong>
        </p>
        <p class="mb-3">
            Disabling 2FA does not change the keys used in authenticator apps. If you wish to change the key
            used in an authenticator app you should <a href="/Account/Manage/ResetAuthenticator">reset your authenticator keys.</a>
        </p>
    </Alert>

    <div class="mt-4">
        <form @formname="disable-2fa" @onsubmit="OnSubmitAsync" method="post">
            <AntiforgeryToken />
            <PrimaryButton Style="ButtonStyle.Red" type="submit">Disable 2FA</PrimaryButton>
        </form>
    </div>
</div>

@code {
    private ApplicationUser _user = default!;

    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;

    protected override async Task OnInitializedAsync()
    {
        _user = await UserAccessor.GetRequiredUserAsync();

        if (HttpMethods.IsGet(HttpContext.Request.Method))
        {
            if (!await UserManager.GetTwoFactorEnabledAsync(_user))
            {
                throw new InvalidOperationException($"Cannot disable 2FA for user as it's not currently enabled.");
            }
            return;
        }
    }

    private async Task OnSubmitAsync()
    {
        var disable2faResult = await UserManager.SetTwoFactorEnabledAsync(_user, false);
        if (!disable2faResult.Succeeded)
        {
            throw new InvalidOperationException($"Unexpected error occurred disabling 2FA.");
        }

        var userId = await UserManager.GetUserIdAsync(_user);
        Logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", userId);
        RedirectManager.RedirectToWithStatus(
            "/Account/Manage/TwoFactorAuthentication",
            "2fa has been disabled. You can reenable 2fa when you setup an authenticator app");
    }
}
